/*
 * src/syntax/get_ll_table.c
 *
 * Harry Wei <harryxiyou@gmail.com>
 * 
 * Get ll(1) analyser table.
 */
#include <stdio.h>
#include <unistd.h>
#include <glib.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include "common.h"
#include "cp_ctrl.h"

static int split2entries(struct la *ctrl, char *buf) {
	ctrl->analyse_table = g_malloc0(sizeof(struct ll_table) * TABLE_SIZE);
	if (NULL == ctrl->analyse_table) {
		g_message("%s -- Allocate error!", __func__);
		return -1;
	}
	ctrl->ll_len = 1;
	struct ll_table *tmp = ctrl->analyse_table;
	gchar **v = g_strsplit(buf, "\n", 0);
	int i = 0;
	g_message("%s -- test lltable", __func__);
	for (i = 0; i < g_strv_length(v) - 1; i++) {
		g_message("%s -- %d is %s", __func__, i, v[i]);
		gchar **_v = g_strsplit(v[i], " ", 4);
		int j = 0;
		char *endptr = NULL;
		sprintf(tmp->vn, "%s", _v[0]);
		sprintf(tmp->vt, "%s", _v[1]);
		sprintf(tmp->pro, "%s", _v[2]);
		tmp->is_last = strtoul(_v[3], &endptr, 0);
		g_message("%s -- %s, %s, %s, %u", __func__, tmp->vn, tmp->vt, tmp->pro, tmp->is_last);
		tmp += 1;
		ctrl->ll_len += 1;
		g_strfreev(_v);
	}
	g_strfreev(v);
	return 0;
}

int get_ll_table(struct la *ctrl) {
	g_message("enter func %s", __func__);
	int fd = open((const char *) LLTABLEFILE, O_RDONLY);
	if (-1 == fd) {
		g_message("%s -- open error!", __func__);
		return -1;
	}
	struct stat fst;
	memset(&fst, 0, sizeof(struct stat));
	fstat(fd, &fst);
	char buf[BUF_LEN];
	memset(buf, '\0', BUF_LEN);
	int ret = 0;
	/*XXX fst.st_size is beyond BUFLEN */
	ret = read(fd, buf, fst.st_size);
	if (ret != fst.st_size) {
		g_message("%s -- read error!", __func__);
		return -1;
	}
	split2entries(ctrl, buf);
	close(fd);
	g_message("leave func %s", __func__);
	return 0;
}
